package pri.zxx.testdemo;

public class IpRangeUtil {
    public static void main(String[] args) {
//        List<String> ipLimit = new ArrayList<>();
//        ipLimit.add("192.168.1.64/26");
//        ipLimit.add("192.168.0.0/16");
//        ipLimit.add("192.168.0.0/24");
//        ipLimit.add("192.168.0.0/32");
//        ipLimit.add("192.168.0.0");
//        String[] ips = new String[]{"192.168.1.127", "192.168.1.2", "192.168.1.1", "192.168.0.0", "192.168.0.0"};
//        Arrays.asList(ips).forEach(s -> {
//            boolean b = ipLimit.stream().anyMatch(s1 -> isInRange(s, s1));
//            Out.println("pass?" + b);
//        });
        System.out.println(isInRange("192.168.9.1", "192.168.10.0/20"));
    }

    /**
     * Ip段匹配
     */
    public static boolean isInRange(String ip, String ipRange) {
        ip = ip.trim();
        ipRange = ipRange.trim();
        String[] ipSegment = ip.split("\\.");
        int ipAddr = (Integer.parseInt(ipSegment[0]) << 24) | (Integer.parseInt(ipSegment[1]) << 16) | (Integer.parseInt(ipSegment[2]) << 8) | Integer.parseInt(ipSegment[3]);
        String maskStr;
        if (!ipRange.contains("/")) {
            maskStr = "32";
        } else {
            maskStr = ipRange.replaceAll(".*/", "");
        }
        int type = Integer.parseInt(maskStr);
        int mask = 0xFFFFFFFF << (32 - type);
        String ipRnageSplit = ipRange.replaceAll("/.*", "");
        String[] ipRangeSegment = ipRnageSplit.split("\\.");
        int cidrIpAddr = (Integer.parseInt(ipRangeSegment[0]) << 24) | (Integer.parseInt(ipRangeSegment[1]) << 16) | (Integer.parseInt(ipRangeSegment[2]) << 8) | Integer.parseInt(ipRangeSegment[3]);
        return (ipAddr & mask) == (cidrIpAddr & mask);
    }
}